package com.yq.servlet;

import com.yq.bean.Product;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(value = "/index",loadOnStartup = 1)
public class ServletIndex extends HttpServlet {

    @Override
    public void init() throws ServletException {
        Product product1 = new Product("1","Iphone13",8888,"us");
        Product product2 = new Product("2","XiaoMi",4444,"op");
        Product product3 = new Product("3","HuaWei",5555,"cj");
        Product product4 = new Product("4","RonYao",6666,"cn");
        ArrayList<Product> productsList = new ArrayList<>();
        productsList.add(product1);
        productsList.add(product2);
        productsList.add(product3);
        productsList.add(product4);
        ServletContext servletContext = getServletContext();
        servletContext.setAttribute("products",productsList);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext servletContext = getServletContext();
        List<Product> productsList = (List<Product>) servletContext.getAttribute("products");
        for (Product product : productsList) {
            response.getWriter().println("<a href='"+request.getContextPath()+"/item?id="+product.getId()+"'>"+product.getName()+"</a>");
        }


    }
}
